class Solution {
public:
    int closestMeetingNode(vector<int>& edges, int node1, int node2) {
        int n=edges.size();

        int ret=n;
        vector<int> vis1(n),vis2(n);
        int x=node1,y=node2;
        while(vis1[x]==0 || vis2[y]==0)
        {
            vis1[x]=vis2[y]=1;
            if(vis1[y])
            {
                ret=y;
            }
            if(vis2[x])
            {
                ret=min(ret,x);
            }
            if(ret<n)
                break;
            if(edges[x]!=-1)
            {
                x=edges[x];
            }
            if(edges[y]!=-1)
            {
                y=edges[y];
            }
        }
        return ret==n?-1:ret;
    }
};
